package io.gitee.zhangbinhub.acp.boot.integration

import io.gitee.zhangbinhub.acp.boot.*
import org.noear.snack.core.Feature
import org.noear.solon.core.AppContext
import org.noear.solon.core.Plugin
import org.noear.solon.core.event.EventBus
import org.noear.solon.scheduling.annotation.Scheduled
import org.noear.solon.scheduling.scheduled.manager.IJobManager
import org.noear.solon.scheduling.scheduled.manager.JobExtractor
import org.noear.solon.scheduling.simple.JobManager
import org.noear.solon.serialization.snack3.SnackRenderFactory

class XPluginImp : Plugin {
    override fun start(context: AppContext) {
        context.beanMake(AcpBootLogConfiguration::class.java)
        context.beanMake(AcpBootAutoConfiguration::class.java)
        context.beanMake(AcpBootComponentAutoConfiguration::class.java)
        context.beanMake(AcpBootInfoAutoConfiguration::class.java)
        context.beanMake(AcpBootSetUpAutoConfiguration::class.java)

        context.lifecycle(Int.MIN_VALUE) {
            context.getBean(SnackRenderFactory::class.java)?.let { factory ->
                factory.addFeatures(Feature.ArrayNullAsEmpty)
                factory.addFeatures(Feature.EnumUsingName)
            }
        }
        initScheduled(context)
    }

    private fun initScheduled(context: AppContext) {
        JobManager.getInstance().let { jobManager ->
            if (!context.beanExtractorHas(Scheduled::class.java)) {
                context.wrapAndPut(IJobManager::class.java, JobManager.getInstance())
                val jobExtractor = JobExtractor(jobManager)
                context.beanBuilderAdd(Scheduled::class.java, jobExtractor)
                context.beanExtractorAdd(Scheduled::class.java, jobExtractor)
                context.lifecycle(Int.MAX_VALUE) {
                    JobManager.getInstance().start()
                }
            }
        }
    }

    override fun stop() {
        JobManager.getInstance().let { jobManager ->
            if (jobManager.isStarted) {
                jobManager.stop()
            }
        }
    }
}